package com.hospicpc.demos.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.hospicpc.demos.commom.Result;
import com.hospicpc.demos.entity.User;
import com.hospicpc.demos.entity.UserInfo;
import com.hospicpc.demos.entity.dto.UserInfoDto;
import com.hospicpc.demos.service.Impl.UserInfoServiceImpl;
import com.hospicpc.demos.service.Impl.UserServiceImpl;
import com.hospicpc.demos.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import static com.hospicpc.demos.utils.JwtUtil.getUserIdByJWT;

@Slf4j
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {
    @Autowired
    UserInfoServiceImpl userInfoService;
    @Autowired
    UserServiceImpl userService;

    @GetMapping("/getByToken")
    public Result getUserByToken(HttpServletRequest httpServletRequest) {
        //获取用户id
        Integer id = getUserIdByJWT(httpServletRequest);

        if(id == 0) {
            return Result.error("服务错误");
        } else {
            //获取数据
            UserInfo u = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("user_id", id));
            UserInfoDto userInfoDto = new UserInfoDto();
            BeanUtil.copyProperties(u,userInfoDto);
            return Result.success(userInfoDto);
        }
    }

    @PostMapping("/updateById")
    public Result updateById(@RequestBody UserInfo userInfo) {
        //更新数据
        boolean res = userInfoService.updateById(userInfo);
        if(res)
            return Result.success("数据保存成功");
        else
            return Result.error("数据更新失败");
    }

    @GetMapping("/getNickNameById")
    public Result getNickNameById(@RequestParam("userId") Long userId) {
        UserInfo one = userInfoService.lambdaQuery().select(UserInfo::getNickName)
                .eq(UserInfo::getUserId, userId).one();

        return Result.success(one);
    }

    @GetMapping("/getByUserId")
    public  Result getByUserId(@RequestParam("userId") Long userId) {
        UserInfo one = userInfoService.lambdaQuery().select(UserInfo::getNickName,UserInfo::getAvatarUrl,UserInfo::getDescription)
                .eq(UserInfo::getUserId, userId).one();

        return Result.success(one);
    }

}
